cmake_minimum_required(VERSION 3.18)
project(proxy2ch)

add_executable(${PROJECT_NAME} main.cpp BBS2chProxyConnection.cpp BBS2chProxyAuth.cpp hmac.c stringEncodingConverter.c BBS2chProxyRawSocket.cpp BBS2chProxySecureSocket.cpp BBS2chProxyHttpHeaders.cpp BBS2chProxyURL.cpp BBS2chProxyKeyManager.cpp BBS2chProxyBoardManager.cpp BBS2chProxyHTML2Dat.cpp BBS2chProxyFormData.cpp BBS2chProxyPoster.cpp utils.cpp parson/parson.c)

set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
find_package(CURL REQUIRED)
find_package(OpenSSL)
find_package(GnuTLS)
find_package(Lua)

set(optional_incs)
set(optional_libs)

if(OPENSSL_FOUND)
	set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DUSE_MITM")
	set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DUSE_MITM")
	list(APPEND optional_incs ${OPENSSL_INCLUDE_DIR})
	list(APPEND optional_libs ${OPENSSL_CRYPTO_LIBRARIES})
	list(APPEND optional_libs ${OPENSSL_SSL_LIBRARIES})
elseif(GNUTLS_FOUND)
	set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DUSE_GNUTLS")
	set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DUSE_GNUTLS -DUSE_MITM")
	list(APPEND optional_incs ${GNUTLS_INCLUDE_DIR})
	list(APPEND optional_libs ${GNUTLS_LIBRARIES})
endif()

if(LUA_FOUND)
	set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DUSE_LUA")
	set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DUSE_LUA")
	list(APPEND optional_incs ${LUA_INCLUDE_DIR})
	list(APPEND optional_libs ${LUA_LIBRARIES})
endif()

if(APPLE)
	find_library(lib_CoreFoundation CoreFoundation REQUIRED)
	list(APPEND optional_libs ${lib_CoreFoundation})
elseif(WIN32)
	list(APPEND optional_libs wsock32 ws2_32 regex)
	set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static-libgcc -static-libstdc++")
else()
	find_package(Iconv REQUIRED)
	if(NOT Iconv_IS_BUILT_IN)
		list(APPEND optional_incs ${Iconv_INCLUDE_DIRS})
		list(APPEND optional_libs ${Iconv_LIBRARIES})
	endif()
	if(NOT OPENSSL_FOUND AND NOT GNUTLS_FOUND)
		message(FATAL_ERROR "OpenSSL or GnuTLS is required!")
	endif()
endif()

target_include_directories(${PROJECT_NAME}
	PRIVATE ${CURL_INCLUDE_DIRS} ${optional_incs}
)

target_link_libraries(${PROJECT_NAME}
	PRIVATE Threads::Threads ${CURL_LIBRARIES} ${optional_libs}
)
